from pony.orm import Database, Required, Set
from django.conf import settings

db = Database()


class Person(db.Entity):
    name = Required(str)
    age = Required(int)
    cars = Set('Car')


class Car(db.Entity):
    make = Required(str)
    model = Required(str)
    owner = Required(Person)


# 连接数据库并创建表的功能
def setup_database():
    """用于连接数据库并生成表"""

    # 绑定数据库连接
    DATABASES_CONFIG = settings.PONY_DATABASES

    db.bind(provider='postgres',
            user=DATABASES_CONFIG['USER'],
            password=DATABASES_CONFIG['PASSWORD'],
            host=DATABASES_CONFIG['HOST'],
            port=DATABASES_CONFIG['PORT'],
            database=DATABASES_CONFIG['NAME'])

    # 通过模型定义的实体创建表
    db.generate_mapping(create_tables=True)

setup_database()
